package com.vsd.service.impl;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.demo.util.SqlUtils;
import com.shopcart.domain.CreditCategory;
import com.vsd.repository.CreditCategoryRepository;
import com.vsd.repository.CreditGoodsRepository;
import com.vsd.service.CreditCategoryService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
@Transactional
public class CreditCategoryServiceImpl implements CreditCategoryService {

	@SuppressWarnings("unused")
	private static final Logger LOGGER = LoggerFactory
			.getLogger(CreditCategoryServiceImpl.class);
	
	@Autowired
	JdbcTemplate jdbcTemplate;
	
	@Autowired
	private CreditCategoryRepository creditCategoryRepository;

	@Override
	public Collection<CreditCategory> findAllByOrderBySortDesc() {
		// TODO Auto-generated method stub
		return creditCategoryRepository.findAllByOrderBySortDesc();
	}

	@Override
	public void save(CreditCategory credit) {
		// TODO Auto-generated method stub
		creditCategoryRepository.save(credit);
	}

	@Override
	public int updateByPrimaryKeySelective(CreditCategory c) {
		// TODO Auto-generated method stub
		try {
			String sql = SqlUtils.update(c, true, " where id = '"+c.getId()+"'");
			return jdbcTemplate.update(sql);
		}catch (Exception e) {
			return 0;
		}
		
	}

	@Override
	public void deleteById(String id) {
		CreditCategory c = creditCategoryRepository.findOne(id);
		//删除该分类下商品
		String sql = "delete from s_credit_goods  where cate_code = '"+c.getCode()+"'";
		jdbcTemplate.execute(sql);
		
		creditCategoryRepository.delete(id);
	}

	@Override
	public CreditCategory findOne(String id) {
		// TODO Auto-generated method stub
		return creditCategoryRepository.findOne(id);
	}

	@Override
	public Page<CreditCategory> findAll(Pageable p) {
		// TODO Auto-generated method stub
		return creditCategoryRepository.findAll(p);
	}

	@Override
	public CreditCategory findByCode(String code) {
		// TODO Auto-generated method stub
		Collection<CreditCategory> list = creditCategoryRepository.findByCode(code);
		if(list.size()>0) return list.iterator().next();
		return null;
	}
	
}
